package com.example.administrator.funchat.fragment;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.funchat.Contans.Config;
import com.example.administrator.funchat.R;
import com.example.administrator.funchat.activity.ErweimaDialog;
import com.example.administrator.funchat.activity.MainActivity;
import com.example.administrator.funchat.activity.MyDialog;
import com.example.administrator.funchat.db.MyselfDatabaseHelper;
import com.example.administrator.funchat.model.User;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.loror.lororUtil.http.HttpUtil;
import com.loror.lororUtil.image.BitmapUtil;

import org.xutils.x;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 个人主页fragment加载
 * Created by Administrator on 2016/6/23.
 */
public class MySelf_fragment extends android.support.v4.app.Fragment implements View.OnClickListener {

    public ImageView myselfBg;
    public ImageView headImage;
    private ImageView erweima;
    private TextView erweimaBiaoshi;
    private TextView myself_name, xinQing, minName, sex, adress;
    private Button changeButton;
    public static final int CHOOSE_PHOTO = 1;
    private String imagePath = null;
    private Drawable drawable;
    private Bitmap bitmap;
    private int s;
    private SQLiteDatabase db;
    private User u;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.myself_tab, container, false);

        myselfBg = (ImageView) view.findViewById(R.id.myself_bg);
        headImage = (ImageView) view.findViewById(R.id.head_image);
        myself_name = (TextView) view.findViewById(R.id.myself_name);
        xinQing = (TextView) view.findViewById(R.id.xinqing);
        minName = (TextView) view.findViewById(R.id.min_name);
        sex = (TextView) view.findViewById(R.id.sex);
        adress = (TextView) view.findViewById(R.id.address);
        changeButton = (Button) view.findViewById(R.id.change_button);
        erweima = (ImageView) view.findViewById(R.id.erweima);
        erweimaBiaoshi = (TextView) view.findViewById(R.id.erweima_tishi);

        myselfBg.setOnClickListener(this);
        headImage.setOnClickListener(this);
        changeButton.setOnClickListener(this);
        erweima.setOnClickListener(this);

        init();
        return view;
    }


    @Override
    public void onStart() {
        super.onStart();
        setInfo();
    }

    //从服务器获取显示个人信息
    private void setInfo() {
        u = MainActivity.u;

        if (u != null) {
            Log.i("login", "setInfo: 显示====");
            x.image().bind(headImage, u.getHeadImg());
            myself_name.setText(u.getName());
            if (!(u.getSignature() == null || u.getSignature().equals(""))) {
                xinQing.setText(u.getSignature());
            }
            minName.setText(u.getName());
            if (!(u.getSex() == null || u.getSex().equals(""))) {
                sex.setText(u.getSex());
            }
            if (!(u.getAddress() == null || u.getAddress().equals(""))) {
                adress.setText(u.getAddress());
            }
        }
    }


    //从SQLite获取信息并更新界面内容
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void init() {
        MyselfDatabaseHelper dbHelper = new MyselfDatabaseHelper(getContext(), "PersonalHomepage.db", null, 1);
        db = dbHelper.getWritableDatabase();
        Cursor cursor = db.query("Myself", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                String nickname = cursor.getString(cursor.getColumnIndex("nickname"));
                String mood = cursor.getString(cursor.getColumnIndex("mood"));
                String sexvalue = cursor.getString(cursor.getColumnIndex("sex"));
                String addressvalue = cursor.getString(cursor.getColumnIndex("address"));
                String bg = cursor.getString(cursor.getColumnIndex("bgImage"));
                String headImage01 = cursor.getString(cursor.getColumnIndex("headImage"));
                String xiaoshiCode = cursor.getString(cursor.getColumnIndex("xiaoshiCode"));
                myself_name.setText(nickname);
                minName.setText(nickname);
                xinQing.setText(mood);
                sex.setText(sexvalue);
                adress.setText(addressvalue);
                if (cursor.getBlob(cursor.getColumnIndex("erweimaImage")) != null && !cursor.getBlob(cursor.getColumnIndex("erweimaImage")).equals("")) {
                    ByteArrayInputStream stream = new ByteArrayInputStream(cursor.getBlob(cursor.getColumnIndex("erweimaImage")));
                    erweima.setBackground(Drawable.createFromStream(stream, "img"));
                }
                if (xiaoshiCode != null && !xiaoshiCode.equals("")) {
                    erweimaBiaoshi.setText(xiaoshiCode);
                }

                if (bg != null && !bg.equals("")) {
                    myselfBg.setBackground(Drawable.createFromPath(bg));
                }
                if (headImage01 != null && !headImage01.equals("")) {
                    headImage.setBackground(Drawable.createFromPath(headImage01));
                }

            } while (cursor.moveToNext());
        }
        cursor.close();

    }


    //界面点击事件监听
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.myself_bg:
                s = 1;
                Intent intent = new Intent("android.intent.action.GET_CONTENT");
                intent.setType("image/*");
                startActivityForResult(intent, CHOOSE_PHOTO);//打开相册
                break;
            case R.id.head_image:
                s = 2;
                Intent intent1 = new Intent("android.intent.action.GET_CONTENT");
                intent1.setType("image/*");
                startActivityForResult(intent1, CHOOSE_PHOTO);//打开相册
                break;
            case R.id.change_button:
                Intent intent2 = new Intent(getContext(), MyDialog.class);
                startActivityForResult(intent2, 10);
                break;
            case R.id.erweima:
                Intent intent3 = new Intent(getContext(), ErweimaDialog.class);
                startActivityForResult(intent3, 100);
                break;
        }
    }


    //请求结果处理
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == Activity.RESULT_OK) {
                    //判断手机号系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        //4.4及以上系统使用这个方法处理图片
                        Log.i("login", "onActivityResult: 111");
                        handleImageOnKitKat(data);
                    } else {
                        //4.4以下系统使用这个方法处理图片
                        Log.i("login", "onActivityResult: 222");
                        handleImageBeforeKitKat(data);
                    }
                }

                break;
            case 10:

                if (data != null) {
                    final User u = (User) data.getSerializableExtra("u");
                    RequestParams p = new RequestParams();
                    p.addBodyParameter("phone", LoginFragment.userPhone);
                    p.addBodyParameter("name", u.getName());
                    p.addBodyParameter("sex", u.getSex());
                    p.addBodyParameter("signature", u.getSignature());
                    p.addBodyParameter("address", u.getAddress());

                    new HttpUtils().send(HttpRequest.HttpMethod.POST, Config.USER_UPDATE, p, new RequestCallBack<String>() {
                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            Log.i("login", "onSuccess: ===========更新结果=" + responseInfo.result);
                            if (responseInfo.result.equals("ok")) {
                                myself_name.setText(u.getName());
                                xinQing.setText(u.getSignature());
                                minName.setText(u.getName());
                                sex.setText(u.getSex());
                                adress.setText(u.getAddress());
                                Log.i("login", "onSuccess: ===========更新结果=成功");
                            } else {
                                Log.i("login", "onSuccess: ===========更新结果=失败");

                            }
                        }

                        @Override
                        public void onFailure(HttpException e, String s) {
                            // Toast.makeText(getActivity(), "网络异常或者服务器异常", Toast.LENGTH_LONG).show();
                        }
                    });


                }
                   /* ContentValues values = new ContentValues();
                    if (!bundle.getString("nickname").equals("")) {
                        values.put("nickname", bundle.getString("nickname"));
                    }
                    if (!bundle.getString("mood").equals("")) {
                        values.put("mood", bundle.getString("mood"));
                    }
                    if (!bundle.getString("sex").equals("")) {
                        values.put("sex", bundle.getString("sex"));
                    }
                    if (!bundle.getString("address").equals("")) {
                        values.put("address", bundle.getString("address"));
                    }
                    if (values != null && !bundle.getString("nickname").equals("") || !bundle.getString("mood").equals("")
                            || !bundle.getString("sex").equal*/
                // s("") || !bundle.getString("address").equals("")){
//                      这里判断是否有数据更新,如果有向服务器发送请求
//                      final Map<String, String> params = new HashMap<>();
//                        if (bundle.getString("nickname").equals("")){
//                            params.put("nickname",bundle.getString("nickname").equals(""));
//                        }
//                        if (bundle.getString("mood").equals("")){
//                            params.put("mood", bundle.getString("mood").equals(""));
//                        }
//                        if (bundle.getString("sex").equals("")){
//                            params.put("sex",bundle.getString("sex").equals(""));
//                        }
//                        if (bundle.getString("address").equals("")){
//                            params.put("address", bundle.getString("address").equals(""));
//                        }
//                      String centerpath = "/MyChat/UserServlet?options=Myself";//这里是个人主页的数据接口
//                      info = WebServicePost.executeHttpPost(params, centerpath);
//                      如果服务器返回结果不等于null 也不为error 说明成功,然后再将数据更新到SQLite
//                      if (info != null && !info.equals("error")) {
                       /* db.update("Myself", values, null, null);
                        init();*/


                break;
            case 100:
                Bundle bundle02 = data.getExtras();
                if (bundle02 != null) {
                    ContentValues values = new ContentValues();
                    if (!bundle02.getString("erweimaImage").equals("")) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        ErweimaDialog.bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                        byte[] result = baos.toByteArray();
                        values.put("erweimaImage", result);
                    }
                    if (!bundle02.getString("xiaoshiCode").equals("")) {
                        values.put("xiaoshiCode", bundle02.getString("xiaoshiCode"));
                    }
                    if (values != null && !bundle02.getString("erweimaImage").equals("") || !bundle02.getString("xiaoshiCode").equals("")) {
//                      这里判断是否有数据更新,如果有向服务器发送请求
//                      final Map<String, String> params = new HashMap<>();
//                        if (bundle02.getString("erweimaImage").equals("")){
//                            params.put("erweimaImage",bundle02.getString("erweimaImage"));
//                        }
//                        if (bundle02.getString("xiaoshiCode").equals("")){
//                            params.put("xiaoshiCode", bundle02.getString("xiaoshiCode"));
//                        }
//                      String centerpath = "/MyChat/UserServlet?options=Myself";//这里是个人主页的数据接口
//                      info = WebServicePost.executeHttpPost(params, centerpath);
//                      }
//                      如果服务器返回结果不等于null 也不为error 说明成功,然后再将数据更新到SQLite
//                      if (info != null && !info.equals("error")) {
                        db.update("Myself", values, null, null);
                        init();
                    }
                }
                break;
            default:
                break;
        }
    }


    //4.4以上版本打开相册
    @TargetApi(19)
    private void handleImageOnKitKat(Intent data) {
        Uri uri = data.getData();
        final ProgressDialog dialog = new ProgressDialog(getActivity());
        dialog.setMessage("正在上传");
        dialog.setCancelable(false);
        dialog.show();
        if (DocumentsContract.isDocumentUri(getContext(), uri)) {
            //如果是document类型的Uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docId.split(":")[1];//解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contentUri = ContentUris.withAppendedId(uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            //如果不是document类型的Uri,则使用普通方式处理
            imagePath = getImagePath(uri, null);
        }
        Log.i("login", "handleImageOnKitKat: ==" + imagePath);
        Bitmap bmp = BitmapUtil.compessBitmap(imagePath, 1024);
        final String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + new File(imagePath).getName();
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(new File(path));
            ByteArrayOutputStream b = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, b);
            fos.write(b.toByteArray());
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.i("login", "handleImageOnKitKat: +" + path);



        //上传图片
        HttpUtil.getInstance().upLoadImage(path, Config.UPDATE_HEAD_IMAGE, new HttpUtil.HttpUtilCallBack() {
            @Override
            public void success(final String s) {

                Log.i("login", "success: 上传成功" + s);
                new File(path).delete();
                if (s != null && !s.equals("")) {
                    //更新头像

                    RequestParams p = new RequestParams();
                    p.addBodyParameter("phone", LoginFragment.userPhone);
                    p.addBodyParameter("path", s);
                    new HttpUtils().send(HttpRequest.HttpMethod.POST, Config.UPDATE_MY_HEAD_IMAGE, p, new RequestCallBack<String>() {
                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            dialog.dismiss();
                            Log.i("login", "onSuccess:====返回== " + responseInfo.result);
                            if (responseInfo.result.equals("ok")) {
                                //更新成功
                                u.setHeadImg(s);
                                new BitmapUtils(getActivity()).display(headImage, s);
                            } else {
                                //更新失败
                                Toast.makeText(getActivity(), "服务器异常错误", Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(HttpException e, String s) {
                            dialog.dismiss();
                            Toast.makeText(getActivity(), "网络异常错误！", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else {
                    dialog.dismiss();
                    Toast.makeText(getActivity(), "上传失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void failed() {
                dialog.dismiss();
                Toast.makeText(getActivity(), "网络异常", Toast.LENGTH_SHORT).show();
                Log.i("上传失败", "failed: ");
                new File(path).delete();
            }
        });

//        这里判断imagePath是否为null或者为空, 向服务器发送请求
//        if (imagePath != null && !imagePath.equals("")){
//          final Map<String, String> params = new HashMap<>();
//          params.put("erweimaImage", bundle02.getString("erweimaImage"));
//          String centerpath = "/MyChat/UserServlet?options=Myself";//这里是个人主页的数据接口
//          info = WebServicePost.executeHttpPost(params, centerpath);
//       }
//       如果服务器返回结果不等于null 也不为error 说明成功,然后再将数据更新到SQLite
//       if(info!=null&&!info.equals("error")){

        /*ContentValues values = new ContentValues();
        if (s == 1) {
            values.put("bgImage", imagePath);
            db.update("Myself", values, null, null);
            init();
        } else if (s == 2) {
            values.put("headImage", imagePath);
            db.update("Myself", values, null, null);
            init();
        }*/

    }


    //4.4版本打开相册处理
    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        imagePath = getImagePath(uri, null);
//       这里判断imagePath是否为null或者为空, 向服务器发送请求
//        if (imagePath != null && !imagePath.equals("")){
//          final Map<String, String> params = new HashMap<>();
//          params.put("erweimaImage", bundle02.getString("erweimaImage"));
//          String centerpath = "/MyChat/UserServlet?options=Myself";//这里是个人主页的数据接口
//          info = WebServicePost.executeHttpPost(params, centerpath);
//       }
//       如果服务器返回结果不等于null 也不为error 说明成功,然后再将数据更新到SQLite
//       if(info!=null&&!info.equals("error")){
        Log.i("login", "handleImageBeforeKitKat: ==" + imagePath);
        ContentValues values = new ContentValues();
       /* if (s == 1) {
            values.put("bgImage", imagePath);
            db.update("Myself", values, null, null);
            init();
        } else if (s == 2) {
            values.put("headImage", imagePath);
            db.update("Myself", values, null, null);
            init();
        }*/
    }

    //通过Uri和selection来获取真实的图片路径
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContext().getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    //根据路径显示图片
//    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
//    private void displayImage(String imagePath) {
//        if (imagePath != null) {
//            bitmap = BitmapFactory.decodeFile(imagePath);
//            drawable = new BitmapDrawable(bitmap);
//            switch (s) {
//                case 1:
//                    myselfBg.setBackground(drawable);
//                    break;
//                case 2:
//                    headImage.setBackground(drawable);
//                    break;
//                default:
//                    break;
//            }
//        } else {
//            Toast.makeText(getContext(), "failed to get image", Toast.LENGTH_SHORT).show();
//        }
//    }


}
